package io.renren.modules.pet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.page.PageData;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.pet.dao.PetLostDao;
import io.renren.modules.pet.dto.PetLostCollectDTO;
import io.renren.modules.pet.entity.PetSendEntity;
import io.renren.modules.pet.enums.PetBreedEnum;
import io.renren.modules.pet.service.PetLostCollectService;
import io.renren.modules.pet.service.PetLostCommentService;
import io.renren.modules.pet.vo.PetLostCollectVO;
import io.renren.modules.pet.vo.PetLostVO;
import io.renren.modules.pet.dto.PetLostDTO;
import io.renren.modules.pet.entity.PetLostEntity;
import io.renren.modules.pet.service.PetLostService;
import io.renren.modules.pet.vo.PetTypeChartPieVO;
import io.renren.modules.security.user.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 丢失宠物信息表
 *
 * @author zwp zwp
 * @since 1.0.0 2025-03-13
 */
@Service
public class PetLostServiceImpl extends CrudServiceImpl<PetLostDao, PetLostEntity, PetLostVO> implements PetLostService {

    @Autowired
    private PetLostCollectService petLostCollectService;

    @Autowired
    private PetLostCommentService petLostCommentService;

    @Override
    public QueryWrapper<PetLostEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String postType = (String)params.get("postType");
        String petBreed = (String)params.get("petBreed");
        String petName = (String)params.get("petName");

        QueryWrapper<PetLostEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.like(StringUtils.isNotBlank(petName), "pet_name", petName);
        wrapper.eq(StringUtils.isNotBlank(postType), "post_type", postType);
        wrapper.eq(StringUtils.isNotBlank(petBreed), "pet_breed", petBreed);
        wrapper.orderByDesc("create_date");

        return wrapper;
    }

    @Override
    public void save(PetLostDTO petLostDTO) {
        PetLostEntity petLostEntity = ConvertUtils.sourceToTarget(petLostDTO, PetLostEntity.class);
        this.insert(petLostEntity);
    }

    @Override
    public void update(PetLostDTO petLostDTO) {
        PetLostEntity petLostEntity = ConvertUtils.sourceToTarget(petLostDTO, PetLostEntity.class);
        this.updateById(petLostEntity);
    }

    @Override
    public List<PetLostVO> petLostList(Map<String, Object> params) {
        List<PetLostEntity> entityList = this.baseDao.selectList(getWrapper(params).eq("status", 1).eq("lost_status", 0));
        List<PetLostVO> petLostVoList = ConvertUtils.sourceToTarget(entityList, PetLostVO.class);
        petLostVoList.forEach(petLostVo -> {
            // 首页图片
            petLostVo.setFirstImageUrl(petLostVo.getImageUrl().split(",")[0]);
        });
        return petLostVoList;
    }

    @Override
    public PetLostVO getInfoById(Long id) {
        PetLostEntity petLostEntity = this.selectById(id);
        PetLostVO petLostVo = ConvertUtils.sourceToTarget(petLostEntity, PetLostVO.class);

        if (petLostVo != null) {
            // 首页图片
            petLostVo.setFirstImageUrl(petLostVo.getImageUrl().split(",")[0]);
            // 照片集合
            petLostVo.setImageUrlList(Arrays.asList(petLostVo.getImageUrl().split(",")));
            // 收藏数量
            List<PetLostCollectVO> petLostCollectVoList = petLostCollectService.getByPetLostId(petLostVo.getId());
            petLostVo.setPetLostCollectNum(petLostCollectVoList.size());
            // 是否已收藏
            // 获取当前用户信息
            Long userId = SecurityUser.getUserId();
            PetLostCollectVO petLostCollectVo = petLostCollectService.getByUserPetLostId(userId, petLostVo.getId());
            if (petLostCollectVo != null) {
                petLostVo.setIsPetLostCollect(1);
            } else {
                petLostVo.setIsPetLostCollect(0);
            }
        }
        return petLostVo;
    }

    @Override
    public List<PetLostVO> listDetailByUser(Map<String, Object> params) {
        // 获取当前用户信息
        Long userId = SecurityUser.getUserId();
        List<PetLostEntity> entityList = this.baseDao.selectList(getWrapper(params).eq("creator", userId).eq("lost_status", 0));
        List<PetLostVO> petLostVoList = ConvertUtils.sourceToTarget(entityList, PetLostVO.class);
        petLostVoList.forEach(petLostVo -> {
            // 首页图片
            petLostVo.setFirstImageUrl(petLostVo.getImageUrl().split(",")[0]);
        });
        return petLostVoList;
    }

    @Override
    public List<PetLostVO> getPetLostCollectByUser(Map<String, Object> params) {
        String postType = (String)params.get("postType");
        String petBreed = (String)params.get("petBreed");
        // 获取当前用户信息
        Long userId = SecurityUser.getUserId();
        List<PetLostCollectVO> petLostCollectVoList = petLostCollectService.getByUserId(userId);
        if (CollectionUtils.isEmpty(petLostCollectVoList)) {
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<PetLostEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", petLostCollectVoList.stream().map(e -> e.getPetLostId()).distinct().collect(Collectors.toList()));
        wrapper.eq(StringUtils.isNotBlank(postType), "post_type", postType);
        wrapper.eq(StringUtils.isNotBlank(petBreed), "pet_breed", petBreed);
        List<PetLostEntity> entityList = this.baseDao.selectList(wrapper);
        List<PetLostVO> petLostVoList = ConvertUtils.sourceToTarget(entityList, PetLostVO.class);
        petLostVoList.forEach(petLostVo -> {
            // 首页图片
            petLostVo.setFirstImageUrl(petLostVo.getImageUrl().split(",")[0]);
        });
        return petLostVoList;
    }

    @Override
    public PageData<PetLostVO> petLostPage(Map<String, Object> params) {
        PageData<PetLostVO> page = this.page(params);
        page.getList().forEach(e -> {
            // 照片集合
            e.setImageUrlList(Arrays.asList(e.getImageUrl().split(",")));
            e.setImageUrlSize(e.getImageUrlList().size());
        });
        return page;
    }

    @Override
    public void examineByUserId(Long reportedUserId, Integer status) {
        UpdateWrapper<PetLostEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("creator", reportedUserId);
        wrapper.set("status", status);
        this.baseDao.update(null, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delLostPetsById(Long id) {
        PetLostEntity petLostEntity = new PetLostEntity();
        petLostEntity.setId(id);
        petLostEntity.setLostStatus(1);
        this.baseDao.updateById(petLostEntity);
    }

    @Override
    public List<PetTypeChartPieVO> getFindLoaderChartPie(Map<String, Object> params) {
        QueryWrapper<PetLostEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("post_type", 1);
        wrapper.eq("status", 1);
        List<PetLostEntity> entityList = this.baseDao.selectList(wrapper);
        if (org.apache.commons.collections.CollectionUtils.isEmpty(entityList)) {
            return Collections.EMPTY_LIST;
        }
        List<PetTypeChartPieVO> list = new ArrayList<>();
        Map<Integer, List<PetLostEntity>> collect = entityList.stream().collect(Collectors.groupingBy(PetLostEntity::getLostStatus));
        collect.keySet().forEach(key -> {
            PetTypeChartPieVO petTypeChartPieVo = new PetTypeChartPieVO();
            petTypeChartPieVo.setName(key == 0 ? "丢失" : "找回");
            petTypeChartPieVo.setValue(collect.get(key).size());
            list.add(petTypeChartPieVo);
        });
        return list;
    }

    @Override
    public List<PetTypeChartPieVO> getFindPetChartPie(Map<String, Object> params) {
        QueryWrapper<PetLostEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("post_type", 0);
        wrapper.eq("status", 1);
        List<PetLostEntity> entityList = this.baseDao.selectList(wrapper);
        if (org.apache.commons.collections.CollectionUtils.isEmpty(entityList)) {
            return Collections.EMPTY_LIST;
        }
        List<PetTypeChartPieVO> list = new ArrayList<>();
        Map<Integer, List<PetLostEntity>> collect = entityList.stream().collect(Collectors.groupingBy(PetLostEntity::getLostStatus));
        collect.keySet().forEach(key -> {
            PetTypeChartPieVO petTypeChartPieVo = new PetTypeChartPieVO();
            petTypeChartPieVo.setName(key == 0 ? "丢失" : "找回");
            petTypeChartPieVo.setValue(collect.get(key).size());
            list.add(petTypeChartPieVo);
        });
        return list;
    }

}